using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UI_SceneFade : MonoBehaviour
{
    public static UI_SceneFade Instance;
    [SerializeField] private Image _fadeImage;

    public bool IsFadeFinish { get; private set; }
    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
    }

    public void DoFadeIn(float duration = 1)
    {
        StartCoroutine(FadeCo(0, 1, duration));
    }
    public void DoFadeOut(float duration = 1)
    {
        StartCoroutine(FadeCo(1, 0, duration));
    }
    private IEnumerator FadeCo(float startAlpha, float targetAlpha, float duration)
    {
        IsFadeFinish = false;
        float timer = 0;
        Color colorLerp = new(0, 0, 0, startAlpha);

        _fadeImage.color = colorLerp;

        while (timer < duration)
        {
            timer += Time.deltaTime;

            float apalh = Mathf.Lerp(startAlpha, targetAlpha, timer / duration);

            colorLerp.a = Mathf.Clamp01(apalh);

            _fadeImage.color = colorLerp;

            yield return null;
        }
        
        IsFadeFinish = true;
    }
}
